package la.renzhen.rtpt.config.source;

import com.ecwid.consul.transport.TLSConfig;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.kv.model.GetValue;
import la.renzhen.rtpt.config.ConfigurationSource;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *
 * @author <a href="mailto:zhouhaichao@2008.sina.com">haiker</a>
 * @version 29/05/2018 10:49 AM
 */
@Slf4j
public class ConsulConfigurationSource implements ConfigurationSource {

    ConsulClient client = null;
    /**
     * consul统一前缀
     */
    String module;

    public ConsulConfigurationSource(String host, int port, String module, TLSConfig tlsConfig) {
        if (tlsConfig == null) {
            this.client = new ConsulClient(host, port);
        } else {
            this.client = new ConsulClient(host, port, tlsConfig);
        }
        this.module = module;
    }

    @Override
    public Map<String, String> loadAll(String environment, String prefix) {
        if (prefix == null) {
            prefix = "";
        }
        Map<String, String> values = new HashMap<>();
        String keyPrefix = String.format("%s/%s/%s", module, environment, prefix);
        int length = String.format("%s/%s/", module, environment).length();
        Response<List<GetValue>> getValues = client.getKVValues(keyPrefix);
        if (getValues.getValue() == null) {
            return values;
        }
        for (GetValue kv : getValues.getValue()) {
            String key = kv.getKey().substring(length);
            String value = kv.getDecodedValue();
            values.put(key, value);
        }
        return values;
    }

    @Override
    public String get(String environment, String key) {
        String realyKey = String.format("%s/%s/%s", module, environment, key);
        GetValue getValue = client.getKVValue(realyKey).getValue();
        if (getValue == null) {
            return null;
        }
        return getValue.getDecodedValue();
    }
}
